package com.car.shopping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.car.commons.core.model.Result;
import com.car.shopping.client.CarAccountClient;
import com.car.shopping.client.CarOrderClient;
import com.car.shopping.client.model.order.GoodOrderInfoDto;
import com.car.shopping.client.model.order.GoodOrderInfoInsertDto;
import com.car.shopping.client.model.user.UserIdRequest;
import com.car.shopping.controller.form.CantCommodityShouhouForm;
import com.car.shopping.entity.CommodityShouhou;
import com.car.shopping.mapper.CommodityShouhouMapper;
import com.car.shopping.service.CommodityShouhouService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.car.shopping.service.dto.CantCommodityShouhouDto;
import com.car.shopping.service.dto.GoodsDto;
import com.car.shopping.service.param.CantCommodityShouhouParam;
import com.car.shopping.service.param.ShoppingSHParam;
import com.car.shopping.util.OSSUtil;
import org.apache.tika.Tika;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 董旭
 * @since 2024-08-28
 */
@Service
public class CommodityShouhouServiceImpl extends ServiceImpl<CommodityShouhouMapper, CommodityShouhou> implements CommodityShouhouService {

   @Autowired
   private CommodityShouhouMapper commodityShouhouMapper;

    @Resource
    private CarAccountClient carAccountClient;

    @Resource
    private CarOrderClient carOrderClient;
    private static final Tika tika = new Tika();

    @Resource
    private OSSUtil ossUtil;


    @Override
    public void shoppingSH(ShoppingSHParam param) throws Exception {
        CommodityShouhou shouhou = new CommodityShouhou();
        shouhou.setCommodityTime(LocalDateTime.now());
        shouhou.setCommodityNum(param.getCommodityNum());
        shouhou.setCommodityCause(param.getCommodityCause());
        //验证图片
        MultipartFile file = param.getCommodityImgs();
        if (file != null &&!isImage(file)) {
            throw new Exception("上传到不是图片");
        }
        InputStream fileContent = file.getInputStream(); // 文件输入流
        String oldName = param.getCommodityImgs().getOriginalFilename();
        String suffix = oldName.substring(oldName.lastIndexOf("."));
        String ImgUrl = ossUtil.uploadFile(fileContent, UUID.randomUUID() + suffix, "ootaoyuoo");
        shouhou.setCommodityImgs(ImgUrl);
        shouhou.setCommodityTracking(param.getCommodityTracking());
        //新订单号是审核通过后再给
        shouhou.setCommodityState(3);//1售后成功2售后失败3待处理
        shouhou.setCommodityReturnid(param.getCommodityReturnid());//1换货2退货
        shouhou.setCommodityUserid(param.getCommodityUserid());
        // 调用 findUserNicknameById
        UserIdRequest userIdRequest = new UserIdRequest();
        userIdRequest.setUserId(param.getCommodityUserid());
        Result<String> result = carAccountClient.findUserNicknameById(userIdRequest);
        System.out.println(result.getData());
        shouhou.setCommodityUsername(result.getData());
        this.save(shouhou);
    }





    @Override
    public void allRight(Integer commodityId) throws Exception {
        // 根据 售后id 查询出对应的 售后 对象
        CommodityShouhou shouhou = this.getById(commodityId);

        if (shouhou == null) {
            throw new Exception("没有找到对应的售后记录");
        }

        shouhou.setCommodityState(1); // 1售后成功2售后失败3待处理

        // 如果 commodityReturnid 不等于 1，退款返回
        if (shouhou.getCommodityReturnid() != 1) {
            // 调用 tuikuan 接口
            System.out.println("单号："+shouhou.getCommodityNum());
            Result tuikuanResult = carOrderClient.tuikuan(shouhou.getCommodityNum());
            System.out.println(tuikuanResult);
            if (tuikuanResult == null || tuikuanResult.getCode() != 200) {
                throw new Exception("调用退货接口失败");
            }
            // 处理 tuikuan 接口的返回结果（如果需要）
            System.out.println("退货结果：" + tuikuanResult.getData());
            // 更新售后记录
            this.updateById(shouhou);
            return;
        }

        // 拿订单id查之前的订单
        String id = shouhou.getCommodityNum();
        Result<GoodOrderInfoDto> orderResult = carOrderClient.findById(id);

//        System.out.println("老订单:"+orderResult);
//        if (orderResult == null || orderResult.getCode() != 200) {
//            throw new Exception("获取旧订单信息失败");
//        }


//        GoodOrderInfoDto oldOrder = orderResult.getData();
//        if (oldOrder == null ) {
//            throw new Exception("获取旧订单信息失败");
//        }
//        System.out.println("111:"+oldOrder);

        // 生成新订单
//        GoodOrderInfoInsertDto newOrderDto = new GoodOrderInfoInsertDto();
//        newOrderDto.setConsigneeName(oldOrder.getUserId());
//        newOrderDto.setConsigneePhone(oldOrder.getConsigneePhone());
//        newOrderDto.setAddress(oldOrder.getAddress());
//
//        // 将旧订单中的商品详情转换为新的商品列表
//        Set<GoodsDto> goodsSet = oldOrder.getOrderDetail().stream().map(detail -> {
//            GoodsDto goodsDto = new GoodsDto();
//            goodsDto.setGoodsId(detail.getGoodsId());
//            goodsDto.setGoodsCont(detail.getGoodsCont()); // 商品数量
//            return goodsDto;
//        }).collect(Collectors.toSet());
//        newOrderDto.setGoods(goodsSet);


        // 调用 FeignClient 生成新订单
        Result insertResult = carOrderClient.huanhuo(id);
        if (insertResult == null || insertResult.getCode() != 200) {
            throw new Exception("生成新订单失败");
        }

        // 更新售后记录
        this.updateById(shouhou);
    }


    @Override
    public void cantCommodityShouhou(CantCommodityShouhouParam param) throws Exception {
        CommodityShouhou shouhou = this.getById(param.getCommodityId());
        // 检查是否找到了对应的售后记录
        if (shouhou == null) {
            throw new Exception("没有找到对应的售后记录");
        }

        //更新驳回原因
        shouhou.setCommodityBohui(param.getCommodityBohui());

        // 更新售后记录状态为驳回状态
        shouhou.setCommodityState(2);

        // 保存更新后的对象到数据库
        this.updateById(shouhou);

    }

    @Override
    public CantCommodityShouhouDto selectShById(Integer commodityId) throws Exception {
        // 1. 根据 commodityId 查询出对应的 CommodityShouhou 对象
        CommodityShouhou shouhou = this.getById(commodityId);

        // 2. 检查是否找到该售后记录
        if (shouhou == null) {
            throw new Exception("未找到对应的售后记录");
        }
        CantCommodityShouhouDto dto = new CantCommodityShouhouDto();
        dto.setCommodityTime(shouhou.getCommodityTime());
        dto.setCommodityNum(shouhou.getCommodityNum());
        dto.setCommodityCause(shouhou.getCommodityCause());
        dto.setCommodityImgs(shouhou.getCommodityImgs());
        dto.setCommodityTracking(shouhou.getCommodityTracking());
        dto.setCommodityReturnid(shouhou.getCommodityReturnid());
        dto.setCommodityState(shouhou.getCommodityState());
        dto.setCommodityBohui(shouhou.getCommodityBohui());
        return dto;
    }

    @Override
    public List<CommodityShouhou> selectAllSh() throws Exception {
        // 使用 MyBatis-Plus 提供的 selectList 方法查询所有记录
        return commodityShouhouMapper.selectList(null);
    }

    // 查询所有换货的售后申请 (CommodityReturnid = 1)
    @Override
    public List<CommodityShouhou> selectHH() throws Exception {
        QueryWrapper<CommodityShouhou> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("commodity_returnid", 1);
        return commodityShouhouMapper.selectList(queryWrapper);
    }

    // 查询所有退货的售后申请 (CommodityReturnid = 2)
    @Override
    public List<CommodityShouhou> selectTH() throws Exception {
        QueryWrapper<CommodityShouhou> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("commodity_returnid", 2);
        return commodityShouhouMapper.selectList(queryWrapper);
    }

    @Override
    public List<CommodityShouhou> selectShByUserId(Integer commodityUserid) throws Exception {
        if (commodityUserid == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        QueryWrapper<CommodityShouhou> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("commodity_userid", commodityUserid);
        return this.list(queryWrapper);
    }


    //判断是否是图片的方法
    private boolean isImage(MultipartFile file) throws Exception {
        String mimeType = tika.detect(file.getInputStream());
        return mimeType != null && mimeType.startsWith("image");
    }
}
